#include <string.h>
#include <iostream>
using std::cout;
using std::endl;


class Computer
{
public:
    Computer(const char * brand,double price)
    : _brand(new char[strlen(brand) + 1]())
    , _price(price)
    {
        _totalPrice += _price;
        strcpy(_brand,brand);
        cout << "Computer(const char *,double)" << endl;
    }

    Computer(const Computer & rhs)
    : _brand(new char[strlen(rhs._brand) + 1]())
    , _price(rhs._price)
    {
        _totalPrice += _price;
        strcpy(_brand,rhs._brand);
        cout << "Computer(const Computer &)" << endl;
    }

    Computer & operator=(const Computer & rhs){
        if(this != &rhs){//1.考虑自复制情况
            _totalPrice -= _price;
            delete [] _brand;//2.回收左操作数的数据成员原本申请的堆空间
            _brand = new char[strlen(rhs._brand) + 1]();//3.深拷贝
            strcpy(_brand,rhs._brand);
            _price = rhs._price;//其他数据成员的复制
            _totalPrice += _price;
            cout << "赋值运算符函数" << endl;
        }
        return *this;//4.返回本对象
    }
    ~Computer(){
        if(_brand){
            delete [] _brand;
            _brand = nullptr;
            _totalPrice -= _price;
        }
        cout << "~Computer()" << endl;
    }

    void print(){
        cout << "brand:" << this->_brand << endl;
        cout << "price:" << this->_price << endl;
    }

    //静态成员函数没有this指针
    static void printTotalPrice(){
        cout << "totalPrice:" << _totalPrice << endl;
        /* cout << "price:" << this->_price << endl; */
    }
private:
    char * _brand;
    double _price;
    static double _totalPrice;
};
double Computer::_totalPrice = 0;

void test0(){
    cout << sizeof(Computer) << endl;

    Computer pc("apple",20000);
    Computer pc2("asus",6000);
    Computer pc3("xiaomi",5000);

    Computer::printTotalPrice();

    /* cout << pc._totalPrice << endl; */
    /* cout << pc2._totalPrice << endl; */
    /* cout << Computer::_totalPrice << endl; */

}

int main(void){
    test0();
    return 0;
}

